package com.example.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.example.mapper.SongMapper;
import com.example.mapper.XmlMapper;
import com.example.model.Song;
import com.example.service.SongService;
import com.github.pagehelper.PageHelper;

import tk.mybatis.mapper.entity.Example;

@Service
public class SongServiceImpl implements SongService {

	@Autowired
	private SongMapper songMapper;

	@Autowired
	private XmlMapper xmlMapper;

	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public void save(Song song) {
		songMapper.insert(song);
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public void update(Song song) {
		// updateByPrimaryKey 更新全部字段,没有值设为null
		// updateByPrimaryKeySelective 只更新需要修改的字段
		songMapper.updateByPrimaryKeySelective(song);
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public void delete(int id) {
		songMapper.deleteByPrimaryKey(id);
	}

	@Override
	@Transactional(propagation = Propagation.SUPPORTS)
	public Song getDetailById(int id) {
		return songMapper.selectByPrimaryKey(id);
	}

	@Override
	@Transactional(propagation = Propagation.SUPPORTS)
	public List<Song> findAll() {
		return songMapper.selectAll();
	}

	@Override
	@Transactional(propagation = Propagation.SUPPORTS)
	public Object querySongListPaged(Song song, Integer page, Integer pageSize) {
		// 开始分页
		PageHelper.startPage(page, pageSize);

		Example example = new Example(Song.class);
		Example.Criteria criteria = example.createCriteria();

		if (song.getName() != "" && song.getName() != null) {
			criteria.andLike("name", "%" + song.getName() + "%");
		}

		example.orderBy("createtime").desc();
		List<Song> songList = songMapper.selectByExample(example);
		int totalCount = songMapper.selectCountByExample(example);
		System.out.println("totalCount:" + totalCount);
		Map<String, Object> resultMap = new HashMap<>();
		resultMap.put("songList", songList);
		resultMap.put("totalCount", totalCount);

		return resultMap;
	}

	@Override
	@Transactional(propagation = Propagation.SUPPORTS)
	public List<Song> querySongListByName(String name) {
		List<Song> songList = xmlMapper.querySongListByName(name);
		return songList;
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public void saveSongTransactional(Song song) {
		songMapper.insert(song);

		int a = 1 / 0;

//		song.setName("夜的第七章");
//		songMapper.updateByPrimaryKeySelective(song);

	}

}
